package ru.averta.notes.dao.impl;

import org.hibernate.SQLQuery;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import ru.averta.notes.dao.TagDao;
import ru.averta.notes.domain.Tag;
import ru.averta.notes.domain.User;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Repository
public class TagDaoImpl extends GenericDaoHibernateImpl<Tag, Long> implements TagDao {

    @Override
	public Tag findByUserAndTitle(User user, String title) {
		return (Tag) createCriteria()
		.add(Restrictions.eq("title", title.toLowerCase()))
		.add(Restrictions.eq("user", user))
		.uniqueResult();
	}

    @Override
    public Collection<Tag> findByTitleAndUser(String title, User user) {
        return createCriteria()
		.add(Restrictions.like("title", title.toLowerCase().replaceAll("%", ""), MatchMode.START))
		.add(Restrictions.eq("user", user))
		.list();
    }

    @Override
    public Set<String> findTagsByUser(User user) {
        SQLQuery query = createSqlQuery("SELECT TAG.Title FROM TAG WHERE (TAG.USER_ID = :userId)");
        query.setLong("userId", user.getId());

        List tags = query.list();
        Set<String> answer = new HashSet<String>(tags.size());
        for (Object tag : tags) {
            answer.add((String) tag);
        }

        return answer;
    }

}
